package App.Repository;

import App.Model.BaseEnum;
import App.Model.ConnectinManager;
import App.Model.ConnectionInfo;
import App.Model.Task.*;

import javax.persistence.Column;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * Created by xw on 2019/4/23.
 */
public class XinGePushRepository extends RawBaseRepository {



    public List<CrmTaskMember> getTaskMember(String recid) throws Exception {

        List<CrmTaskMember> _tasks = new ArrayList<>();
        Connection conn = null;
        try {
            conn = getConnection(url, username, password);
            PreparedStatement st = conn.prepareStatement("  select tm.*, u.username from crm_task_member tm " +
                                                                " left join crm_user u on tm.userid = u.id " +
                    "where tm.recstatus = 1 and u.recstatus = 1 and taskid = ? ");
            st.setString(1, recid);
            ResultSet rs = st.executeQuery();
            ResultSetMetaData metadata = rs.getMetaData();
            while (rs.next()) {
                int _userid = rs.getInt("userid");
                String _username = rs.getString("username");
                int _ishost = rs.getInt("ishost");
                int _ismanager = rs.getInt("ismanager");
                CrmTaskMember _member = new CrmTaskMember();
                _member.setUserid(_userid);
                _member.setUsername(_username);
                if(_ishost == 1)
                    _member.setIshost(true);
                else
                    _member.setIshost(false);
                if(_ismanager == 1)
                    _member.setIsmanager(true);
                else
                    _member.setIsmanager(false);
                _tasks.add(_member);
            }
            rs.close();
            conn.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            conn.close();
        }
        return _tasks;
    }


    public List<CrmTask> getTaskInfo(String recid) throws Exception {

        List<CrmTask> _tasks = new ArrayList<>();
        Connection conn = null;
        try {
            conn = getConnection(url, username, password);
            PreparedStatement st = conn.prepareStatement(" select * from crm_task where recid= ? ");
            st.setString(1, recid);
            ResultSet rs = st.executeQuery();
            ResultSetMetaData metadata = rs.getMetaData();
            while (rs.next()) {
                Date _beginTime = rs.getTimestamp("begintime");
                String _content = rs.getString("content");
                String _addressname = rs.getString("address_name");

                CrmTask _task = new CrmTask();
                _task.setBegintime(_beginTime);
                _task.setContent(_content);
                _task.setAddressname(_addressname);
                _tasks.add(_task);
            }
            rs.close();
            conn.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            conn.close();
        }
        return _tasks;
    }


    public List<CrmTaskReminder> getTaskReminders() throws Exception {

        List<CrmTaskReminder> _reminders = new ArrayList<>();
        Connection conn = null;
        try {
            conn = getConnection(url, username, password);
            Statement stmt = conn.createStatement();
            String _strSql = " select tr.*,(select count(1) from crm_project_task where taskid=tr.taskid) as hasproject from crm_task_reminder tr " +
                    " inner join crm_task t on tr.taskid=t.recid " +
                    " where t.taskstatus!=2  " +
                    " and  tr.recstatus=1 and t.recstatus =1 ";
            ResultSet rs = stmt.executeQuery(_strSql);

            ResultSetMetaData metadata = rs.getMetaData();
            while (rs.next()) {
                String _recid = rs.getString("recid");
                int _repeattype = rs.getInt("repeattype");
                int _minutes = rs.getInt("reminder_minute");
                int _aheadtype = rs.getInt("aheadtype");
                String _taskid = rs.getString("taskid");
                int _hasProject = rs.getInt("hasproject");

                CrmTaskReminder _reminder = new CrmTaskReminder();
                _reminder.setRecid(_recid);
                _reminder.setTaskid(_taskid);
                _reminder.setRepeattype(_repeattype);
                _reminder.setMinutes(_minutes);
                _reminder.setAheadtype(_aheadtype);
                _reminder.setHasproject(_hasProject);
                _reminders.add(_reminder);

            }
            rs.close();
            conn.close();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            conn.close();
        }
        return _reminders;
    }

    private Date getNewBeginTime(Calendar cal, int _aheadValue, int _aheadtype) {

        if (_aheadtype == BaseEnum.TaskAheadType.Minute.getTaskAheadType()) {
            cal.add(Calendar.MINUTE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
            cal.add(Calendar.HOUR, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Day.getTaskAheadType()) {
            cal.add(Calendar.DATE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Month.getTaskAheadType()) {
            cal.add(Calendar.MONTH, -_aheadValue);
        }
        return cal.getTime();
    }


    private TaskScheduleInfo createScheduleInfo(TaskReminder _r, Calendar cal) {


        //重复方式: 一次，每天，每周
        int _repeattype = _r.getRepeattype();

        //提前分钟数
        int _aheadValue = _r.getAheadvalue();

        //提前时间的类型：时，分，秒，天，
        int _aheadtype = _r.getAheadtype();

        //caculate schedule run time
        if (_aheadtype == BaseEnum.TaskAheadType.Minute.getTaskAheadType()) {
            cal.add(Calendar.MINUTE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
            cal.add(Calendar.HOUR, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Day.getTaskAheadType()) {
            cal.add(Calendar.DATE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Month.getTaskAheadType()) {
            cal.add(Calendar.MONTH, -_aheadValue);
        }


        java.util.Date _scheduleStartDate = cal.getTime();

        int _year = cal.get(Calendar.YEAR);
        //calender 的月份从0 开始，所以要加1
        int _month = cal.get(Calendar.MONTH) + 1;
        int _day = cal.get(Calendar.DATE);
        int _hour = cal.get(Calendar.HOUR_OF_DAY);
        int _minute = cal.get(Calendar.MINUTE);
        int _second = cal.get(Calendar.SECOND);
        int _week = cal.get(Calendar.DAY_OF_WEEK);
        // _week = _week + 1;
        System.out.println("current week:" + _week);

        //create cron 表达式

        //把秒数设置为0
        _second = 0;

        String _cronString = String.format("0 %s %s %s %s ? %s", _minute, _hour, _day, _month, _year);

        if (_repeattype == BaseEnum.TaskRepeatType.Once.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s %s ? %s", _second, _minute, _hour, _day, _month, _year);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Day.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s * * ?", _second, _minute, _hour);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Week.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s ? * %s", _second, _minute, _hour, _week);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Month.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s * ?", _second, _minute, _hour, _day);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Year.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s %s ? *", _second, _minute, _hour, _day, _month);
        }


        TaskScheduleInfo _info = new TaskScheduleInfo();
        _info.setCronstring(_cronString);
        _info.setBegindatetime(_scheduleStartDate);

        return _info;
    }


    public int savePushHistory(String taskid, String reminderid, String content, String pushRequest, String pushResponse, String deviceType) throws Exception {

        int _result = 0;
        Connection conn = null;
        try {

            conn = getConnection(url, username, password);
            PreparedStatement st = conn.prepareStatement(" insert into crm_xinge_push_history(reccreator,recid,push_request,push_response,devicetype,taskid,reminderid,push_content)" +
                    "  values(1,?,?,?,?,?,?,?) ");
            st.setString(1, UUID.randomUUID().toString());
            st.setString(2, pushRequest);
            st.setString(3, pushResponse);
            st.setString(4, deviceType);

            st.setString(5, taskid);
            st.setString(6, "");
            st.setString(7, content);
            _result = st.executeUpdate();
            conn.close();

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            conn.close();
        }
        return _result;
    }
}
